<?php
/**
 * Created by PhpStorm.
 * User: 江桥
 * QQ：1062241667
 * Date: 2016/9/20
 * Time: 10:09
 */

namespace Company\Controller;

use Think\Controller;

class ScanOrderController extends BaseController
{	
	//根据设置返回对应订单号
	public function mailno_status($order_no){
		$mailno_status=C('base_config.mailno_status');
		if($mailno_status==1){
			C('scanorder.lang_name','面单');
			if(empty($order_no)){
				return alert('0','请输入面单号');
			}
			$porder_info=M("Pushorder",C('DB_PRS'),C('DB_DEPOT'))->where(array('logistics_no'=>$order_no))->find();

			if(!empty($porder_info)){
				return $porder_info['order_no'];
			}else{
				return alert('0','当前面单号找不到对应商品');
			}
		}else{
			C('scanorder.lang_name','订单');
			if(empty($order_no)){
				return alert('0','请输入订单号');
			}
			return $order_no;
		}
	}
    public function index()
    {	
		$mailno_status=C('base_config.mailno_status');
		
		if($mailno_status==1){
			C('scanorder.lang_name','面单');
		}else{
			C('scanorder.lang_name','订单');
		}
		
		$this->assign('basket_nums',C('base_config.basket_nums'));
        $this->display();
    }
	public function index_iframe(){
		$this->display();
	}
	public function packing_iframe(){
		$this->display();
	}
	public function weighting_iframe(){
		$this->display();
	}
    public function get_goods()
    {
        $orderno = I('orderno');
		$orderno=$this->mailno_status($orderno);
		
        if ($orderno == '') {
            return alert_message('0', '请输入'.C('scanorder.lang_name').'信息');
        }
        $info=M("Pushorder",C('DB_PRS'),C('DB_DEPOT'))->field('id,box_no')->where("order_no='$orderno'")->find();
		$id=$info['id'];
        $result =M("Pushordergoods",C('DB_PRS'),C('DB_DEPOT'))->join("__GOODS__ on __PUSHORDERGOODS__.goods_no=__GOODS__.goods_no",'LEFT')->where("order_id='$id'")->select();

        if($result){
			echo json_encode(array('flag'=>1,'data'=>$result,'box_no'=>$info['box_no']));
			exit;
        }
        else{
            return alert('0','当前'.C('scanorder.lang_name').'号找不到对应商品');
        }
    }

    public function post_goods()
    {//将信息提交到数据库、、记录订单号和筐号
        if (!IS_POST) {
            die;
        }
        $orderno = I("post.orderno");
        $kno = I("post.kno");
        $orderno = explode(',', $orderno);
        $kno = explode(',', $kno);
        if ($orderno == '' || $kno == '' || count($orderno) != count($kno)) {
            return alert('0', '操作有误');
        }
        foreach ($kno as $k => $v) {
            $data[] = array('pack_num' => $kno[$k], 'order_id' => $orderno[$k]);
        }
        ///////订单号验证、、、存在，则返回错误
        $map['order_id'] = array('in', $orderno);
        if (M("packlist",C('DB_PRS'),C('DB_DEPOT'))->where($map)->count() > 0) {
            return alert('0', '该条记录已经存在');
        }
        if (M('packlist',C('DB_PRS'),C('DB_DEPOT'))->addAll($data)) {
            return alert('1', '操作成功');
        }
        return alert('0', '操作失败');
    }

    //////////打包//////////
    public function packing()
    {
		$mailno_status=C('base_config.mailno_status');
		if($mailno_status==1){
			C('scanorder.lang_name','面单');
		}else{
			C('scanorder.lang_name','订单');
		}
        $this->display();
    }

    //扫描  验证当前订单是否已退货（拦截，暂不开发）  以及订单是否存在
    public function paking_order()
    {
        $Pushorder = M("Pushorder",C('DB_PRS'),C('DB_DEPOT'));
        $Goods = M("Pushordergoods",C('DB_PRS'),C('DB_DEPOT'));
        $where = array();
		$orderno = I("get.index");
		$orderno=$this->mailno_status($orderno);

        $where['order_no'] = $orderno;
        if ($Pushorder->where($where)->count() == 0) {
            alert('0', C('scanorder.lang_name').'不存在！');
        }
        if (M("Printorder",C('DB_PRS'),C('DB_DEPOT'))->where($where)->getField('is_inout') >= 1) {
            alert('0', '该'.C('scanorder.lang_name').'已经出库！');
        }
        if(M("Intercept_order",C('DB_PRS'),C('DB_DEPOT'))->where($where)->count() >= 1){
            alert('0', '注意：该'.C('scanorder.lang_name').'已被拦截！不能打包！');
        }
        $order_id = $Pushorder->where($where)->getField('id');

        $result = $Goods->where("order_id='$order_id'")->select();
		
        if (count($result) == 0) {
            alert('0', '该'.C('scanorder.lang_name').'没有商品');
        }else{
			foreach($result as $k=>$v){
				$barcode=M('Goods',C('DB_PRS'),C('DB_DEPOT'))->field('bar_code')->where('goods_no="'.$v['goods_no'].'"')->find();
				$result[$k]['bar_code']=$barcode['bar_code'];
			}
			alert('1', $result);
		}
    }

    public function paking_package()
    {
        if (I("get.index") == '') {
            alert('0', '请输入耗材条形码！');
        }
        $where['pn'] = I("get.index");
        $Pack = M("PackageMaterial",C('DB_PRS'),C('DB_DEPOT'));
        $result = $Pack->where($where)->find();
		// echo $Pack->getlastsql();
		// die;
        if (count($result) == 0) {
            alert('0', '耗材不存在！');
        }
        alert('1', $result);
    }

    public function packing_post()
    {
        $P = M("Packing",C('DB_PRS'),C('DB_DEPOT'));
        if (I("post.package") == '') {
            alert('0', '操作有误！');
        }
		$orderno = I("post.order_no");
		$orderno=$this->mailno_status($orderno);
		
        $data['order_no'] = $orderno;
        if($P->where("order_no='{$data['order_no']}'")->count()>=1){
            alert(0,'该'.C('scanorder.lang_name').'已经打包！');
        }
        $package = ltrim(I("post.package"), ',');
        $package = explode(',', $package);
        $new_arr = array();
        $new_count = array();
        foreach ($package as $v) {
            if (in_array($v, $new_arr)) {
                $index = array_search($v, $new_arr);
                $new_count[$index] = $new_count[$index] + 1;
            } else {
                $new_arr[] = $v;
                $new_count[] = 1;
            }
        }
        $data['all_pack_pn'] = implode(',', $new_arr);
        $data['all_pack_count'] = implode(',', $new_count);
        $data['order_no'] = $orderno;
        $vv = M("package_material",C('DB_PRS'),C('DB_DEPOT'));
        foreach ($new_arr as $k => $v) {///减去耗材数量
            $id = $vv->where("pn='$v'")->getField('id', true);
            foreach ($id as $i) {
                $count = $vv->where("id='$i'")->getField('quantity-a_quantity as count');
                if ($count >= $new_count[$k]) {
                    $vv->where("id='$i'")->setInc('a_quantity', $new_count[$k]);
                    break 1;
                } else {
                    $vv->where("id='$i'")->setInc('a_quantity', $count);
                    $new_count[$k] = $new_count[$k] - $count;
                }
            }
        }
        $tiji=0;
        foreach($id as $m){//计算耗材的体积
            $n_v=$vv->where("id='$m'")->getField('l_w_h');
            $n_v=explode('_',$n_v);
            $tiji=$tiji+$n_v[0]*$n_v[1]*$n_v[2];
        }
        $data['pack_v']=$tiji;
        if ($P->add($data)) {
            alert('1', I("post.order_no"));
        } else {
            alert('0', '操作失败');
        }
    }

    //////////称重
    public function weighed(){
        $weight=I("post.weight");
		
        $order_no=I("post.order_no");
		$order_no=$this->mailno_status($order_no);
		
        $P=M("Packing",C('DB_PRS'),C('DB_DEPOT'));
        if ($weight == '') {
            alert('0', '操作有误！');
        }
        if(!is_numeric($weight)){
            alert('0', '重量必须为数字！');
        }
        $data['order_no'] = $order_no;
        if(M("Pushorder",C('DB_PRS'),C('DB_DEPOT'))->where("order_no='{$data['order_no']}'")->count()==0){
            alert(0,'该'.C('scanorder.lang_name').'不存在！');
        }
        if($P->where("order_no='{$data['order_no']}'")->count()==0){
            alert(0,'该'.C('scanorder.lang_name').'还没有打包！');
        }
        if($P->where("order_no='{$data['order_no']}' and pack_weight is null")->count()<=0){
            alert(0,'该包裹已经称重！');
        }
        $Pushorder = M("Pushorder",C('DB_PRS'),C('DB_DEPOT'));
        if($Pushorder->where("order_no='{$order_no}'")->getField('trade_model')==1){//跨境
            $return=$this->get_method();
        }
        $data['pack_weight']=$weight;
        if($P->where("order_no='{$order_no}'")->save($data)){
			//计算快递费用-begin
			$pushorder=M("Pushorder",C('DB_PRS'),C('DB_DEPOT'));
			$map_pushorder['order_no']=$data['order_no'];
			$pushorder_info=$pushorder->where($map_pushorder)->find();//订单信息
			$EmsCompany=M("EmsCompany",C('DB_PRS'),C('DB_DEPOT'));
			$EmsFee=M("EmsFee",C('DB_PRS'),C('DB_DEPOT'));
			$emsc_info=$EmsCompany->where(array('code'=>$pushorder_info['logistics_business']))->find();//物流企业信息
			$p_info=$P->where(array('order_no'=>$data['order_no']))->find();//打包信息
			$vol_weight=$p_info['pack_v']/$emsc_info['vol_weight'];//体积重量=体积/换算常量
			if($vol_weight>$pack_weight){//体积重量大于实际重量
				$fee_weight=$vol_weight;
			}else{
				$fee_weight=$pack_weight;
			}//得到实际计算重量
			$province=$pushorder_info['province'];
			$emsfee_info=$EmsFee->where(array('area'=>array('like',"%$province%")))->find();//找到计费节点
			//计算费用
			if($fee_weight<=$emsfee_info['first_weight']){
				$ems_fee=$emsfee_info['first_price'];//快递费用
			}else{
				$ems_fee=$emsfee_info['first_price']+($fee_weight-$emsfee_info['first_weight'])/$emsfee_info['second_weight']*$emsfee_info['second_price'];//首重+续重(超出费用/续重单位数量*续重单位价格)
			}
			$res_fee=$pushorder->where($map_pushorder)->setField('ems_fee',$ems_fee);//更新快递费用信息
			//计算快递费用-end
			
            alert(1,'操作成功！');
        }
        else{
            alert(0,'操作失败！');
        }
    }

    public function weighting(){
		$mailno_status=C('base_config.mailno_status');
		if($mailno_status==1){
			C('scanorder.lang_name','面单');
		}else{
			C('scanorder.lang_name','订单');
		}
        $this->display();
    }
	
	//出库接口（更新出库信息）
	private function get_method(){
		// $status=M('Pushorder',C('DB_PRS'),C('DB_DEPOT'))->where(array('order_no'=>I("post.order_no")))->setField('is_delivery',1);
		$order_no=I("post.order_no");
		$order_no=$this->mailno_status($order_no);
		if($status!==false){
			$url=C('BASE_CONFIG.get_method');//更新出库信息

			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL, $url);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_TIMEOUT,60);//单位秒,也可以使用
			//post传值数据
			curl_setopt($ch, CURLOPT_POST, 1);
			//post的变量
			curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('order_no'=>$order_no)));
			$output = curl_exec($ch);
			curl_close($ch);
			return json_decode($output,true);
		}else{
			// M('Pushorder')->where(array('order_no'=>I("post.order_no")))->setField('is_delivery',0);//回滚操作
			$this->error('更新出库信息出错，请检查程序');
		}
    }
}